import { app, BrowserWindow, ipcMain, screen } from 'electron'

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`

function createWindow () {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    width: 390,
    height: 280,
    useContentSize: true,
    frame: false, // 无边窗口,
    resizable: false,
    transparent: true
  })
  mainWindow.state = {}

  mainWindow.loadURL(winURL) // 渲染页面

  mainWindow.on('closed', () => {
    mainWindow = null
  })

}

app.on('ready', createWindow)

// 当所有窗口关闭时候结束进程
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})
// 关闭窗口
ipcMain.on('close-win', () => {
  mainWindow.close()
})
// 最小化窗口
ipcMain.on ('minsize-win', () => {
  mainWindow.minimize()  
})
// 最大化窗口
ipcMain.on('maxsize-win', () => {
  // 判断是不是已经最大化了 最大化还原
  if (mainWindow.state.isMaximized) { 
    mainWindow.state.isMaximized = false
    mainWindow.setBounds(mainWindow.state.Bounds)
    // mainWindow.restore()
  } else {
    mainWindow.state.isMaximized = true
    mainWindow.state.Bounds = mainWindow.getBounds()
    mainWindow.maximize()
  }
})

// 用户登录 调整窗口大小
ipcMain.on('user-login', () => {
  let {width: screenWidth, height: screenHeight} = screen.getPrimaryDisplay().workAreaSize
  let winWidth = 888
  let winHeight = 500
  mainWindow.setResizable(true)
  mainWindow.setBounds({
    x: ~~(screenWidth/2 - winWidth/2),
    y: ~~(screenHeight/2 - winHeight/2),
    width: winWidth,
    height: winHeight
  })
})


